#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <stdbool.h>

char *removeKdigits(char *num, int k) {
    int n = strlen(num);
    int top = 0;
    char *stk = calloc((n + 1), sizeof(char));
    char test[n + 1];
    for (int i = 0; i < n; ++i) {
        while (top && stk[top] > num[i] && k) {
            top--;
            k--;
        }
        stk[++top] = num[i];
    }
    memcpy(test, stk,n + 1);
    top -= k;
    char *ans = calloc(n + 1, sizeof(char));
    int ansSize = 0;
    bool isLeadingZero = true;
    for (int i = 1; i <= top; ++i) {
        if (isLeadingZero && stk[i] == '0') {
            continue;
        }
        isLeadingZero = false;
        ans[ansSize++] = stk[i];
    }
    if (ansSize == 0) {
        ans[0] = '0';
        ans[1] = 0;
    } else {
        ans[ansSize] = 0;
    }
    return ans;
}

int main() {

    char *num = "1432219";
    int k = 3;
    char *ret = removeKdigits(num, k);
    printf("%s\n", ret);
    printf(" start\n");
}